/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package dcm4che;

import java.io.File;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

import DBConnections.MySQL_Query;
import DBConnections.ServerData;
import GUI.JFrameBase;
import libraries.FileLibrary;
import libraries.LanguageLibrary;
import libraries.PathLibrary;
import libraries.SystemCall;
import model.DB2Hash;
import view.Server;


/**
 *
 * @author aeguzkiza
 *
 * USAGE:
 * 1.- SetServerData
 * 2.- SetOptions
 * 3.- Run dcmSND for each acquisition name.
 */
public class dcmSND {

    public static class MyException extends Exception {
        static final int SystemCallError = 1;
        private int type;
        private String string;

        public MyException(int type, String string) {
            super();
            this.type = type;
            this.string = string;
        }

        @Override
        public String getMessage() {
            switch (type) {
                case SystemCallError:
                    return "CONFIGURACIÓN DEL SERVIDOR POSIBLEMENTE INCORRECTA.\nPara resolver el problema revise la ventana de configuración.\n\nHa surgido un fallo de comunicación con el PACS al realizar la siguiente llamada cmd:\n["+string+" ]";
            default:
                    return "ERROR DESCONOCIDO: string = "+string+" type = "+type;
            }
        }
    }
    // Loading libraries
    MySQL_Query DB = new MySQL_Query();
    SystemCall SC = new SystemCall();
    PathLibrary PL = new PathLibrary();
    LanguageLibrary LL = new LanguageLibrary();
    FileLibrary FLib = new FileLibrary();
    
    // Global variables 
    private String pathLibrary = PL.getdcm4chePath();   // Get's the path where library is located.
    public String inPath = PL.getimgs2sendPath();
    private ResultSet rs;
        
    private String options = "";
    private String inPathOption = "";
    
    
    private String dcm4che = null;
    private String cmd = null;
    private String buffer = null;
    private boolean isError = false;
    private String error = "";
    
    
    /*public dcmSND() throws MyException, SQLException{   // Only gets files on folder. Allows to do all the process manually.
        ArrayList FolderpathList = FLib.getFilesOnFolder(inPath,".dcm|.DCM"); // Gets dicom file paths from a selected folder.
    }*/

    public dcmSND(JFrameBase frame, String acquisition) throws MyException, SQLException, FileLibrary.MyException{     // Follows all the sending process.
        System.out.println("<<<<< START OF DCMSND >>>>>");
        
        if(frame.selectedServerComboBox.getSelectedIndex() <= 0){
            String error = "No se ha seleccionado el servidor de destino.\nVuelva a intentar el envío una vez se haya seleccionado.";
            throw new MyException(MyException.SystemCallError, error );
        }else{
            Server selectedServer = (Server) frame.selectedServerComboBox.getSelectedItem();
            System.out.println("selectedServer: "+selectedServer);
            DB2Hash server = selectedServer.getServer();

            System.out.println("selectedServer: "+server.get("AETitle")+"@"+server.get("HostIP")+":"+server.get("HostPort"));
            System.out.println("pathLibrary: "+this.pathLibrary);
            System.out.println("pathImages: "+this.inPath+"\n");

            // Gets the server data saved in database.
            ArrayList FolderpathList = FLib.getFilesOnFolder(inPath,".dcm|.DCM"); // Gets dicom file paths from a selected folder.

            System.out.println("acquisition: "+acquisition+" FolderpathList: "+FolderpathList);
            String File2Send = FLib.isInFolder(inPath,acquisition,FolderpathList);

            // DCM4CHE2 VIA COMMAND LINE:
            String pathDcmsnd = pathLibrary+"\\dcmsnd";
            this.dcm4che = "\""+pathDcmsnd+"\" "+options+" "+server.get("AETitle")+"@"+server.get("HostIP")+":"+server.get("HostPort")+" "+inPathOption+" \""+File2Send+"\"";
            this.cmd = "cd \""+pathLibrary+"\" && "+dcm4che+"\n";
            String buffer = null;
            try{
                Object result[] = SC.SystemCall(cmd);
                this.isError = Boolean.valueOf(result[0].toString());         // Cast Object to boolean.
                this.error = "Error en los parámetros de configuración del envío";
                this.buffer = (String) result[1];
                System.out.println("ERROR RESULT: "+error);
            }catch(Exception ex){
                Logger.getLogger(JFrameBase.class.getName()).log(Level.SEVERE, null, ex);
            }

            System.out.println("cmd: "+cmd);
            System.out.println("buffer: "+buffer+"\n");

            if(isError == true){
                String CmdSliced = "cd \""+pathLibrary+"\"\n && \""+pathDcmsnd+"\"\n "+options+" "+server.get("AETitle")+"@"+server.get("HostIP")+":"+server.get("HostPort")+" "+inPathOption+" \n\""+File2Send+"\"";    // The cmd call have been sliced to show it on an alert window.
                throw new MyException(MyException.SystemCallError, CmdSliced );}    // Error check.
            // Deletes a file from the temp folder after checking if is sent to the PACS.
            String[] var0 = new String[]{"1"};  // Write send=1 on database for the corresponding acquisition.
            DB.SQLupdate("UPDATE acquisition SET Sent=? WHERE AcquisitionName='"+acquisition+"'",false,var0.length,var0);
            DB.closeConnection();
            boolean deleted = FLib.deleteFile(File2Send);    // Delete the DCM file AFTER sending it (original JPG file stays saved).
        }
        System.out.println("<<<<< END OF DCMSND >>>>>");
    }    
    
    public String getInPath(){
        return this.inPath;
    }
    public void setOptions(String options){
        this.options = options;
    }
    /*    
    public String getOptions(){
        return this.options;
    }
    public String getInPathOption(){
        return this.inPathOption;
    }
    public String getInPath(){
        return this.inPath;
    }*/
    public String getDcm4che(){
        return this.dcm4che;
    }
    public String getCMD(){
        return this.cmd;
    }
    public String getBuffer(){
        return this.buffer;
    }    
    public String getError(){
        return this.error;
    }
}
